import {config} from './config.js'
 var CryptoJS = require('./crypto-js.js')
 // 签名密钥
 const SECRET_KEY = "method-url-body-timestamp-nonce-123456789-abcdefg-@#$%&*.?";
 // 生成随机字符串 
 function generateNonce() {
   return Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15) + Math.random().toString(36).substring(2, 15);
 }
 // 递归排序函数
 function sortObject(obj) {
   if (obj === null || typeof obj !== "object") {
       return obj; // 如果是 null 或非对象，直接返回
   }
 
   if (Array.isArray(obj)) {
       // 对数组中的每个元素递归排序
       return obj.map(sortObject);
   }
 
   // 对对象的键名排序并递归处理值
   return Object.keys(obj)
       .sort()
       .reduce((sorted, key) => {
           sorted[key] = sortObject(obj[key]);
           return sorted;
       }, {});
 }
// 生成富文本节点
function generateRichTextNode(text) {
  let tempStr = text
  let richTextNode = []
  let leftBracketIndex = tempStr.indexOf('[')
  let rightBracketIndex = tempStr.indexOf(']')
  let countOfWord = 0
  Array.from(tempStr).map(item => {
    if (item != '[' && item != ']') {
      countOfWord++
    }
  })
  if (leftBracketIndex == -1 || rightBracketIndex == -1 || countOfWord == 0) {//没有emoji
    richTextNode.push({
      type: 'text',
      text: tempStr
    })
    return richTextNode
  }
  while (tempStr.length != 0) {
    leftBracketIndex = tempStr.indexOf('[')
    rightBracketIndex = tempStr.indexOf(']')
    if (leftBracketIndex == 0) { // 开头是[
      rightBracketIndex = tempStr.indexOf(']')
      if (rightBracketIndex == -1) {
        richTextNode.push({
          type: 'text',
          text: tempStr
        })
        tempStr = ''
      } else {
        let emojiName = tempStr.slice(0, rightBracketIndex + 1)
        if (emoji[emojiName]) { // 有效emoji
          richTextNode.push({
            name: 'img',
            attrs: {
              width: '20rpx',
              height: '20rpx',
              src: emoji[emojiName].img
            }
          })
        } else {//无效emoji
          richTextNode.push({
            type: 'text',
            text: emojiName
          })
        }
        tempStr = tempStr.substring(rightBracketIndex + 1, tempStr.length)
      }
    } else { // 开头不是[
      if (leftBracketIndex == -1) {// 最后全是文字
        richTextNode.push({
          type: 'text',
          text: tempStr.slice(0, tempStr.length)
        })
        tempStr = ''
      } else {
        richTextNode.push({
          type: 'text',
          text: tempStr.slice(0, leftBracketIndex)
        })
        tempStr = tempStr.substring(leftBracketIndex, tempStr.length + 1)
      }
    }
  }
  return richTextNode
}

//输入Unix时间戳，返回指定时间格式
function calcTimeHeader(time) {
  // 格式化传入时间
  let date = new Date(time)
  let year = date.getUTCFullYear()
  let month = date.getUTCMonth()
  let day = date.getDate()
  let hour = date.getHours()
  let minute = date.getUTCMinutes()
  // 获取当前时间
  let currentDate = new Date()
  let currentYear = date.getUTCFullYear()
  let currentMonth = date.getUTCMonth()
  let currentDay = currentDate.getDate()
  // 计算是否是同一天
  if (currentYear == year && currentMonth == month && currentDay == day) {//同一天直接返回
    if (hour > 12) {
      return `下午 ${hour}:${minute < 10 ? '0' + minute : minute}`
    } else {
      return `上午 ${hour}:${minute < 10 ? '0' + minute : minute}`
    }
  }
  // 计算是否是昨天
  let yesterday = new Date(currentDate - 24 * 3600 * 1000)
  if (year == yesterday.getUTCFullYear() && month == yesterday.getUTCMonth && day == yesterday.getDate()) {//昨天
    return `昨天 ${hour}:${minute < 10 ? '0' + minute : minute}`
  } else {
    return `${year}-${month + 1}-${day} ${hour}:${minute < 10 ? '0' + minute : minute}`
  }
}

function toast(text, mask = true, icon = 'none') { //弹框
  setTimeout(() => {
    wx.showToast({
      title: text,
      icon: icon,
      mask: mask,
    })
    setTimeout(() => {
      wx.hideToast();
    }, 2000)
  }, 0)
}


//获取微信的code
function _getCode() {
  var code = ''
  return new Promise((resolve, reject) => {
    wx.checkSession({
      success: function (res) {
        console.log(res, '成功的checkSession')
        resolve(res)
      },
      fail: function (res) {
        console.log(res, '失败的checkSession')
        wx.login({
          success: function (res) {
            resolve(res.code)
          },
          fail: function (res) {
            reject(res)
          }
        })
      }
    })
  })
}

function getPageList(api, _this, url, params, isClickTab) { //分页  isClickTab true:是tab点的 false:是普通的滚动加载
  console.log('--------------------------',url)
  return new Promise((resolve, reject) => {
    _this.setData({
      isShowKong: false, //空的图标隐藏
      hasMore: true //当进来数据最下面显示‘玩了命的加载中’
    })
    if (params.pageNum == 1) {
      _this.setData({
        pageNum: 1,
        pageList: []
      });
    }

    api.$get(url, params).then((res) => {
      console.log(res.data)
      if (res.data.rows.length > 0) {
        _this.setData({
          pageList: isClickTab ? res.data.rows : _this.data.pageList.concat(res.data.rows), //当前某个更新数据
          pageNum: _this.data.pageNum + 1,
          isLodingLock: true, // 当前某个锁关闭
          hasMore: false,
        });
      } else {
        _this.setData({
          hasMore: false //当加载完所有数据最下面显示‘没有跟多数据了’
        })
      }
      if (_this.data.pageList.length == 0) {
        _this.setData({
          isShowKong: true
        })
      }
      resolve(res)
    })
  })
}



function payMentTow(_this, common, _data) { //订单支付
  return new Promise((resolve, reject) => {
    var params = {
      id: _data.order_id, //订单id
      attach: _data.attach //
    }

    common.post('lore/api/pay', params, (res) => { //1.调取后台支付拿到支付信息
      wx.hideLoading()

      //#ifdef H5
      jweixin.ready(() => {   //需在用户可能点击分享按钮前就先调用
        jweixin.chooseWXPay({
          timestamp: res.data.timeStamp, // 支付签名时间戳，注意微信jssdk中的所有使用timestamp字段均为小写。但最新版的支付后台生成签名使用的timeStamp字段名需大写其中的S字符
          nonceStr: res.data.nonceStr, // 支付签名随机串，不长于 32 位
          package: res.data.package, // 统一支付接口返回的prepay_id参数值，提交格式如：prepay_id=\*\*\*）
          signType: res.data.package, // 签名方式，默认为'SHA1'，使用新版支付需传入'MD5'
          paySign: res.data.package, // 支付签名
          success: () => {
            common.get('lore/api/payResult', params, (res) => {
              console.log(res, '支付成功.....')
              resolve(res); //支付成功
            })
          },
          fail(res) {
            console.log(res, '支付失败.....')
            reject(res) //支付失败
          }
        })
      })
      //#endif

      //#ifdef MP-WEIXIN
      wx.requestPayment({ // 2.调取微信支付接口
        timeStamp: res.data.timeStamp,
        nonceStr: res.data.nonceStr,
        package: res.data.package,
        signType: res.data.package,
        paySign: res.data.package,
        success(res) {
          common.get('lore/api/payResult', params, (res) => {
            console.log(res, '支付成功.....')
            resolve(res); //支付成功
          })
        },
        fail(res) {
          console.log(res, '支付失败.....')
          reject(res) //支付失败
        }
      })
      //#endif

    }, true)
  });
}

const authorize = (setting) => { // 重复获取权限操作
  return new Promise((resolve, reject) => {
    wx.getSetting({ // 跳转掉去页面
      success: (response) => {
        if (!response.authSetting[setting] && response.authSetting[setting] !== undefined) { //如果用户没有允许相关权限再次提示重新询问开启相关权限
          wx.showModal({
            title: '提示',
            content: '使用此功能请先在小程序设置中授权',
            success:  (res) => {
              if (res.confirm) {
                wx.openSetting({ // 选择具体某个授权
                  success(tag) {
                    if (tag.authSetting[setting]) { // 用户在设置页选择同意授权
                      console.log(tag, '&&同意里层&&')
                      resolve(true)
                    }
                  },
                  complete: (response) =>{
                    if(!response.authSetting[setting]){
                      console.log(response, '&&拒绝里层&&')
                      reject()
                    }
                  }
                });
              } else if (res.cancel) {
                reject()
              }
            },
          })
        } else {
          resolve(true)
        }
      },
      fail: (response) =>{
        console.log(response, '&&拒绝外层&&')
        reject()
      }
    })
  })
}

//检测是否为空
function isNull(e) {
  return e == undefined || e == "undefined" || e == null || e == "" || e.length == 0
}

//获取手机号
function getPhoneNumber(common, iv, encryptedData) {
  return new Promise((resolve, reject) => {
    var params = {
      iv,
      encryptedData
    }
    common.get('lore/api/phone', params, (res) => {
      if (res.code == 201) {
        wx.navigateTo({
          url: '/pages/author/author'
        })
      } else {
        resolve(res); //获取手机号成功
      }
    })
  })
}

function getDom_01(id) { //获取dom信息 (适用于普通的dom)
  return new Promise((resolve, reject) => {
    wx.createSelectorQuery().select('#' + id).boundingClientRect((rect) => {
      if (rect) {
        resolve(rect)
      } else {
        reject('$$DOM元素没有获取到$$')
      }
    }).exec((res) => {
    })
  })
}


function getDom_02(id) { //适合获取 scroll-view
  return new Promise((resolve, reject) => {
    wx.createSelectorQuery().select('#' + id).fields({
      dataset: true,
      size: true,
      scrollOffset: true,
      properties: ['scrollX', 'scrollY'],
      context: true,
    }, function (res) {
      if (res) {
        resolve(res)
      } else {
        reject('DOM元素没有获取到')
      }
    }).exec()
  })
}

function getSystemInfo() { //获取到设备信息
  return new Promise((resolve, reject) => {
    wx.getSystemInfo({
      success(res) {
        resolve(res)
      },
      fail(res) {
        reject(res)
      }
    })
  })
}

function previewImage(arr, c_img = '') { //图片预览
  wx.previewImage({
    current: c_img,
    urls: arr,
    success: (res)=>{
    }
  })
}

function formatNumber(n) { // 1转换成01
  n = n.toString()
  return n[1] ? n : '0' + n
}

function getCurrentDate() { //处理当前时间转换成各种格式
  var today = new Date() //时间对象
  var year = today.getFullYear() //年
  var month = today.getMonth() + 1 //月
  var day = today.getDate() //日
  var week = today.getDay() //天
  var hour = today.getHours() //时
  var minute = today.getMinutes() //分
  var second = today.getSeconds() //秒

  function getFullDate() { //2018/01/01
    return [year, month, day].map(formatNumber).join('-')
  }

  function getYearMonth() { //2018/01
    return [year, month].map(formatNumber).join('-')
  }

  function getYear() { //2018
    return year
  }

  function getMonthDay() { //01/01
    return [month, day].map(formatNumber).join('-')
  }

  function getFullHourMinute() { //09:00
    return [hour, minute].map(formatNumber).join(':')
  }

  function getFullTime() { //09:00:00
    return [hour, minute, second].map(formatNumber).join(':')
  }

  function getMonth() { //09
    return month
  }

  function getDay() { //09
    return day
  }

  function getHour() { //09
    return hour
  }

  function getMinute() { //09
    return minute
  }

  return {
    getFullDate,
    getYear,
    getYearMonth,
    getMonthDay,
    getFullHourMinute,
    getFullTime,
    getMonth,
    getDay,
    getHour,
    getMinute
  }
}

// 昨天
function getPreDay(date) {
  var day = new Date(date).getTime() - 24 * 60 * 60 * 1000
  return new Date(day).getFullYear() + "-" + formatNumber(new Date(day).getMonth() + 1) + "-" + formatNumber(new Date(
    day).getDate());
}

// 明天
function getNextDay(date) {
  var day = new Date(date).getTime() + 24 * 60 * 60 * 1000
  return new Date(day).getFullYear() + "-" + formatNumber(new Date(day).getMonth() + 1) + "-" + formatNumber(new Date(
    day).getDate());
}

/**
 * 获取上一个月
 *
 * @date 格式为yyyy-mm-dd的日期，如：2014/01/25
 */
function getPreMonth(date, n = 1) {
  var arr = date.split('-');
  var year = arr[0]; //获取当前日期的年份
  var month = arr[1]; //获取当前日期的月份
  var day = arr[2]; //获取当前日期的日
  var days = new Date(year, month, 0);
  days = days.getDate(); //获取当前日期中月的天数
  var year2 = year;
  var month2 = parseInt(month) - 1;
  if (month2 <= 0) {
    year2 = parseInt(year2) - 1;
    month2 = 12
  }
  var day2 = day;
  var days2 = new Date(year2, month2, 0);
  days2 = days2.getDate();
  if (day2 > days2) {
    day2 = days2;
  }
  if (month2 < 10) {
    month2 = '0' + month2;
  }
  var t2 = year2 + '-' + month2 + '-' + day2;
  return t2;
}

/**
 * 获取下一个月
 *
 * @date 格式为yyyy-mm-dd的日期，如：2014/01/25
 */
function getNextMonth(date, n = 1) {

  var arr = date.split('-');
  var year = arr[0]; //获取当前日期的年份
  var month = arr[1]; //获取当前日期的月份
  var day = arr[2]; //获取当前日期的日
  var days = new Date(year, month, 0);
  days = days.getDate(); //获取当前日期中的月的天数
  var year2 = year;
  var month2 = parseInt(month) + n;
  if (month2 >= 13) {
    year2 = parseInt(year2) + 1;
    month2 = 1;
  }
  var day2 = day;
  var days2 = new Date(year2, month2, 0);
  days2 = days2.getDate();
  if (day2 > days2) {
    day2 = days2;
  }
  if (month2 < 10) {
    month2 = '0' + month2;
  }
  var t2 = year2 + '-' + month2 + '-' + day2;
  return t2;
}

function uploadFile(url, filePath, name,formData) { //上传文件
  wx.showLoading({
    title: '正在上传中...'
  });
  // 当前时间戳（毫秒）
  const timestamp = Date.now().toString();
  //随机字符串
  const nonce = generateNonce();
  // 拼接签名内容
  const dataToSign = 'POST' + url.replace(config.baseURL,'') + '{}' + timestamp + nonce;
  console.log(dataToSign)
  // 使用 HMAC-SHA256 算法生成签名
  const signature = CryptoJS.HmacSHA256(dataToSign, SECRET_KEY).toString(CryptoJS.enc.Hex);
  return new Promise((resolve, reject) => {
    wx.uploadFile({
      url,
      filePath,
      name,
      formData: formData,
      header: {
        'dataType': "json",
        'Content-Type': 'multipart/form-data',
        'Authorization': 'Bearer ' + wx.getStorageSync('token'),
        'X-Timestamp':timestamp,
        'X-Nonce':nonce,
        'X-Signature':signature,
      },
      success: (res) => {
        var data = JSON.parse(res.data);
        resolve(data)
        wx.hideLoading()
      },
      fail: (res) =>{
        console.log(res, '$$上媒体失败$$')
      }
    })
  })
}

function timeToNumber(val) { //时间转换成数字 09:00:00 转换成900000
  if (val) {
    return val.split(':').join('') << 1 >> 1
  }
}


function getQrcodeParams(common, id) { //获取二维码参数
  return new Promise((resolve, reject) => {
    common.get('lore/api/qrcodeParams', {
      id
    }, res => {
      if (res.code == 200) {
        resolve(res.data.params)
      } else { //容错跳转到首页
        toast('当前小程序码已失效')
        wx.reLaunch({
          url: '../../home/index'
        })

      }
    })
  })
}

function getDateTime(date) { //获取时间戳
  return new Date(date).getTime()
}

function dateFromString(time) { // 解决ios系统 new Data()的bug
  if (!time) {
    return
  }
  time = time.replace(/-/g, ':').replace(' ', ':')
  time = time.split(':')
  var time1 = new Date(time[0], (time[1] - 1), time[2], time[3], time[4], time[5])
  return time1
}

function parseQuery(query) {  // &xxx=xxx&xxx=xxx 转换成对象
  var reg = /([^=&\s]+)[=\s]*([^&\s]*)/g;
  var obj = {};
  while (reg.exec(query)) {
    obj[RegExp.$1] = RegExp.$2;
  }
  return obj;
}



function linkurl (url, type) { //跳转 url: 地址 type：类型
    switch (type) {
      case 'redirect':
        wx.redirectTo({
          url,
        })
        break;
      case 'reLaunch':
        wx.reLaunch({
          url,
        })
        break;
      case 'back':
        wx.navigateBack({
          delta: 1
        })
        break;
        case 'switchTab':
          wx.switchTab({
            url,
          })
          break;
      default:
        if (getCurrentPages().length > 8) {
          wx.redirectTo({
            url,
          })
        } else {
          wx.navigateTo({
            url
          })
        }
    }
}

function formCollect  ($,api,from_id)  {  // 手机formid
  api.$post(api.main.formId, {formIdList: [from_id]}).then((res) => {
    console.log(res, '$$formid$$')
  })
}

function detail(e) {  // 拿去htmldata参数
  return e.currentTarget.dataset
}

function formConfig (i){ // 获取表单信息
  var formConfig = [
    {
      key: '',
      url: ''
    }
  ]
  return formConfig[i]
}



function transformTime(timestamp = +new Date()) { // 时间戳转时间
    if (timestamp) {
        var time = new Date(timestamp);
        var y = time.getFullYear();
        var M = time.getMonth() + 1;
        var d = time.getDate();
        var h = time.getHours();
        var m = time.getMinutes();
        var s = time.getSeconds();
      return y + '-' + formatNumber(M) + '-' + formatNumber(d) + ' ' + formatNumber(h) + ':' + formatNumber(m) + ':' + formatNumber(s);
      } else {
          return '';
      }
}

function call(phoneNumber){ //打电话
  wx.makePhoneCall({
    phoneNumber
  })
}
// ArrayBuffer转16进制字符串
function buf2hex(buffer) {
  var hexArr = Array.prototype.map.call(
    new Uint8Array(buffer),
    function (bit) {
      return ('00' + bit.toString(16)).slice(-2)
    }
  )
  return hexArr.join('');
}
// 16进制字符串转ArrayBuffer
function hex2buf(hex) {
  return new Uint8Array(hex.match(/[\da-f]{2}/gi).map((h) => {
    return parseInt(h, 16)
  })).buffer
}

// 字符串转成2个一组的字符串协议的数组方便获取数据
function buffer2xy(buffer) {
  let dataView = new DataView(buffer)
  let dataResult = []
  for (let i = 0; i < dataView.byteLength; i++) {
    dataResult.push(dataView.getUint8(i).toString(16))
  }
  return dataResult
}
function getbyteArray(hexString){
  const byteArray = [];
  for (let i = 0; i < hexString.length; i += 2) {
      const byte = hexString.substring(i, i + 2);
      byteArray.push(parseInt(byte, 16));
  }
  return byteArray
 }
function throttle(me, key, fn, delay = 1000) { 
  let pre = me.data[key]
  return function () {
    let now = + new Date();
    if (now - pre >= delay) {
      fn.apply(me, arguments)
      pre = now
      me.setData({
        [key]: now
      })
    }
  }
}
function inArray(arr, key, val) {
  for (let i = 0; i < arr.length; i++) {
    if (arr[i][key] === val) {
      return i;
    }
  }
  return -1;
}
function findLastIndex(arr, predicate) {
  let index = arr.length;
  while (index--) {
    if (predicate(arr[index])) return index;
  }
  return -1;
}
module.exports = { 
  toast,
  getPageList,
  payMentTow,
  authorize,
  isNull,
  getPhoneNumber,
  getDom_01,
  getDom_02,
  getSystemInfo,
  previewImage,
  formatNumber,
  getCurrentDate,
  uploadFile,
  timeToNumber,
  getQrcodeParams,
  getDateTime,
  dateFromString,
  getPreDay,
  getNextDay,
  getPreMonth,
  getNextMonth,
  parseQuery,
  linkurl,
  formCollect, 
  generateRichTextNode,
  calcTimeHeader,
  detail,
  formConfig,
  transformTime,
  call,
  hex2buf,
  buffer2xy,
  buf2hex,
  getbyteArray,
  throttle,
  inArray,
  findLastIndex
}
